//
//  BCHeadLetterTableViewController.m
//  aiteshangcheng
//
//  Created by mac on 2017/6/8.
//  Copyright © 2017年 aite. All rights reserved.
//

#import "BCHeadLetterTableViewController.h"
#import "BCLetterPopViewController.h"
#import "BCHeadLetterTableViewCell.h"
#import "Utility.h"
#import "BCHeadSendLetterTableViewController.h"
#import "Datahandle.h"
#import "AFHTTPRequestOperationManager.h"
//#import "Header.h"
#define kScreanWidth   [UIScreen mainScreen].bounds.size.width
//判断字符串是否为空
#define isStringEmpty(a) ([a isEqual:[NSNull null]] || a == nil || [a isEqualToString:@""])
@interface BCHeadLetterTableViewController ()<UIPopoverPresentationControllerDelegate,BCLetterPopViewControllerDelegate>

@property (nonatomic, strong) NSArray *letterArray;

@property (nonatomic, strong) NSMutableArray *cellHeightArray;

@property (nonatomic, strong) NSMutableArray *cellOtherIsHidden;

@end

@implementation BCHeadLetterTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.cellHeightArray = [NSMutableArray array];
    self.cellOtherIsHidden = [NSMutableArray array];
   
    [self getDataInfoWithString:@"index.php?act=member_message&op=systemmsg"];
}
-(void)backTwo
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   // self.tabBarController.tabBar.hidden = YES;
     [self setNAV];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 导航栏设置
- (void)setNAV{
    //ICON_64_
//    [self.navigationController.navigationBar setBackgroundImage:[self createImageWithColor:[UIColor orangeColor]] forBarMetrics:UIBarMetricsDefault];
//    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
//    [title setBackgroundColor:[UIColor clearColor]];
//    [title setTextAlignment:NSTextAlignmentCenter];
//    title.textColor = [UIColor whiteColor];
//    title.font = [UIFont systemFontOfSize:20];
//    title.text = @"站内信列表";
//    [title sizeToFit];
//    self.navigationItem.titleView = title;
//    CGRect rect = title.frame;
//    title.frame = CGRectMake((kScreanWidth - rect.size.width)/2, (44 - rect.size.height)/2, rect.size.width, rect.size.height);
//
//    UIBarButtonItem *back = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"] style:UIBarButtonItemStyleDone target:self action:@selector(backTwo)];
//    self.navigationItem.leftBarButtonItem = back;
    
//    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
//    [button setImage:[UIImage imageNamed:@"1_03_2"] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(addViewController:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem *addItem = [[UIBarButtonItem alloc]initWithCustomView:button];
//    self.navigationItem.rightBarButtonItem = addItem;
    self.navigationController.navigationBar.hidden = false;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:222.0f/255.0f green:60.0f/255.0f blue:50.0f/255.0f alpha:1];
    self.title = @"消息中心";
    [self.navigationController.navigationBar setTintColor:UIColor.whiteColor];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:17],
       NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
    self.tableView.tableFooterView = [UIView new];
    
}
//根据颜色生成图片
- (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
#pragma mark - 返回上一级界面
- (void)backHomeViewController{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 请求网络数据
- (void)getDataInfoWithString:(NSString *)codeString{
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@",REMOTEURL,codeString];
    [self httpRequest:urlString and:@{@"key" : DHNetworkManager.shareManager.userAccount.key} and:0];
}

- (void)httpRequest:(NSString *)urlStr and:(NSDictionary *)dict and:(NSInteger)num
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    __weak typeof(self) weakSelf = self;
    [manager GET:urlStr parameters:dict success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSData *resData = [[NSData alloc] initWithData:[operation.responseString dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"123 %@", resultDic);
        NSInteger code = [[resultDic objectForKey:@"code"] integerValue];
        if (num == 0) {
            if (code == 200) {
                [weakSelf.cellHeightArray removeAllObjects];
                [weakSelf.cellOtherIsHidden removeAllObjects];
                weakSelf.letterArray = resultDic[@"datas"][@"message_array"];
                for (int i = 0; i < self.letterArray.count; i ++) {
                    [weakSelf.cellHeightArray addObject:@(60)];
                    [weakSelf.cellOtherIsHidden addObject:@"NO"];
                }
                [weakSelf.tableView reloadData];
                
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        alert(nil, AFTfailStr);
    }];
}

#pragma mark - 站内信点击事件
- (void)addViewController:(UIButton *)button{
    BCLetterPopViewController *letterPopViewController = [[BCLetterPopViewController alloc]init];
    letterPopViewController.delegate = self;
    letterPopViewController.modalPresentationStyle = UIModalPresentationPopover;
    letterPopViewController.popoverPresentationController.sourceView = button;
    letterPopViewController.popoverPresentationController.sourceRect = button.bounds;
    letterPopViewController.popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirectionAny;
    //设置代理
    letterPopViewController.popoverPresentationController.delegate = self;
    //显示弹出控制器
    [self presentViewController:letterPopViewController animated:YES completion:nil];
}

#pragma mark - UIPopoverPresentationControllerDelegate
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

#pragma mark - BCLetterPopViewControllerDelegate
//收到的站内信
- (void)haveGettedLetter:(UIButton *)button{
    NSLog(@"收到的站内信");
    [self getDataInfoWithString:@"index.php?act=member_message&op=message"];
}

//系统消息
- (void)haveSendLetter:(UIButton *)button{
    NSLog(@"系统消息");
    [self getDataInfoWithString:@"index.php?act=member_message&op=systemmsg"];
}
//私信
- (void)letter:(UIButton *)button{
    NSLog(@"私信");
    [self getDataInfoWithString:@"index.php?act=member_message&op=personalmsg"];
    
}
//我要发送站内信
- (void)sendLetter:(UIButton *)button{
    NSLog(@"我要发送站内信");
    BCHeadSendLetterTableViewController *sendLetter = [[BCHeadSendLetterTableViewController alloc]init];
    [self.navigationController pushViewController:sendLetter animated:YES];
}

//显示站内信内容
- (void)showContentButtonClicked:(UIButton *)button{
    self.cellOtherIsHidden[button.tag - 10000] = [self.cellOtherIsHidden[button.tag - 10000] isEqualToString:@"NO"] ? @"YES" : @"NO";
    if ([self.cellOtherIsHidden[button.tag - 10000] isEqualToString:@"NO"]) {
        self.cellHeightArray[button.tag - 10000] = @(60);
        
    }
    else
    {
        NSDictionary *letterDic = self.letterArray[button.tag - 10000];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreanWidth - 20, 40)];
        label.font = [UIFont systemFontOfSize:15];
        label.text = letterDic[@"message_body"];
        label.numberOfLines = 0;
        [label sizeToFit];
        
        
        self.cellHeightArray[button.tag - 10000] = @(60 + 20 + label.frame.size.height);
    }
//    button.selected = !button.selected;
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return self.letterArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCHeadLetterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BCHeadLetterTableViewCell"];
    if (!cell) {
        cell = [[BCHeadLetterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"BCHeadLetterTableViewCell"];
        
        cell.showContentButton.selected = NO;
    }
    NSDictionary *letterDic = self.letterArray[indexPath.section];
    cell.titleLabel.text = letterDic[@"from_member_name"];
    cell.timeLabel.text = [self timeStrIntervalSince:letterDic[@"message_time"] withModel:@"yyyy-MM-dd HH:mm"];
    cell.showContentButton.tag = 10000 + indexPath.section;
    [cell.showContentButton addTarget:self action:@selector(showContentButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    if ([self.cellOtherIsHidden[indexPath.section] isEqualToString:@"NO"]) {
        cell.otherView.hidden = YES;
        cell.showContentButton.selected = NO;
    }else{
        cell.otherView.hidden = NO;
        cell.showContentButton.selected = YES;
    }
    cell.contentLabel.text = letterDic[@"message_body"];
    cell.contentLabel.numberOfLines = 0;
    [cell.contentLabel sizeToFit];
    CGRect contentRect = cell.contentLabel.frame;
    cell.contentLabel.frame = CGRectMake(contentRect.origin.x, contentRect.origin.y, kScreanWidth - 20, contentRect.size.height);
    return cell;
}

#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [self.cellHeightArray[indexPath.section] floatValue];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
